import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:media_kit/media_kit.dart';
import 'app/routes/app_pages.dart';
import 'app/data/services/user_service.dart';
import 'app/data/services/api_service.dart';
import 'app/data/services/alarm_service.dart';
import 'app/data/services/channel_service.dart';
import 'app/data/services/video_service.dart';
import 'app/data/services/playback_service.dart';
import 'app/data/services/record_service.dart';
import 'app/data/services/file_service.dart';
import 'app/data/services/base_service.dart';
import 'app/data/services/search_history_service.dart';
import 'app/modules/download/controllers/download_controller.dart';
import 'app/widgets/global_download_indicator.dart';
import 'package:fvp/fvp.dart' as fvp;

void main() async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化MediaKit（支持H.265）
  MediaKit.ensureInitialized();

  fvp.registerWith();

  // 初始化GetStorage
  await GetStorage.init();

  // 初始化GetX服务
  _initServices();

  runApp(const MyApp());
}

// 初始化服务
void _initServices() {
  // 按顺序注册服务：UserService -> ApiService -> AlarmService -> ChannelService -> VideoService -> PlaybackService -> RecordService -> FileService -> SearchHistoryService
  Get.put(UserService(), permanent: true);
  Get.put(ApiService(), permanent: true);
  Get.put(AlarmService(), permanent: true);
  Get.put(ChannelService(), permanent: true);
  Get.put(VideoService(), permanent: true);
  Get.put(PlaybackService(), permanent: true);
  Get.put(RecordService(), permanent: true);
  Get.put(FileService(), permanent: true);
  Get.put(SearchHistoryService(), permanent: true);
  Get.put(DownloadController(), permanent: true);
}

// 获取初始路由
String _getInitialRoute() {
  try {
    final userService = Get.find<UserService>();
    final isLoggedIn = userService.isLoggedIn;

    // 如果用户已登录，自动设置全局认证信息
    if (isLoggedIn) {
      final baseService = BaseService();
      baseService.setAuth(userService.token, userService.tenantId);
      print('应用启动时已设置全局认证信息');
    }

    return isLoggedIn ? Routes.TABBAR : Routes.LOGIN;
  } catch (e) {
    print('获取初始路由错误: $e，默认跳转到登录页');
    return Routes.LOGIN;
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(750, 1624),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context, child) {
        return GetMaterialApp(
          title: "华数灵眸",
          initialRoute: _getInitialRoute(),
          getPages: AppPages.routes,
          debugShowCheckedModeBanner: false,
          // 配置语言为中文
          locale: const Locale('zh', 'CN'),
          localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: const [
            Locale('zh', 'CN'), // 中文
          ],
          // 配置bot_toast
          builder: (context, child) {
            return Stack(
              children: [
                BotToastInit()(context, child),
                const GlobalDownloadIndicator(),
              ],
            );
          },
          navigatorObservers: [BotToastNavigatorObserver()],
        );
      },
    );
  }
}
